package cn.hengzhu.main_manager.service.impl;

import java.io.Serializable;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

import cn.hengzhu.main_manager.utils.task.QuertzTask;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;

import cn.hengzhu.main_manager.repository.dao.ManageCaseBoxMapper;
import cn.hengzhu.main_manager.repository.dao.ManageCaseMapper;
import cn.hengzhu.main_manager.repository.dao.ManageCaseTypeMapper;
import cn.hengzhu.main_manager.repository.dao.SysConstMapper;
import cn.hengzhu.main_manager.repository.domain.ManageCase;
import cn.hengzhu.main_manager.repository.domain.ManageCaseBox;
import cn.hengzhu.main_manager.repository.domain.ManageCaseBoxExample;
import cn.hengzhu.main_manager.repository.domain.ManageCaseExample;
import cn.hengzhu.main_manager.repository.domain.ManageCaseType;
import cn.hengzhu.main_manager.repository.domain.ManageCaseTypeExample;
import cn.hengzhu.main_manager.repository.domain.SysConst;
import cn.hengzhu.main_manager.repository.domain.SysConstExample;
import cn.hengzhu.main_manager.repository.vo.CaseByDoorPutReidsVO;
import cn.hengzhu.main_manager.repository.vo.CaseByDoorVO;
import cn.hengzhu.main_manager.repository.vo.CaseInfoPutRedisVO;
import cn.hengzhu.main_manager.repository.vo.CaseInitVO;
import cn.hengzhu.main_manager.repository.vo.WeiXinTokenVO;
import cn.hengzhu.main_manager.service.ManageCaseService;
import cn.hengzhu.main_manager.utils.AliMsmUtils;
import cn.hengzhu.main_manager.utils.HttpClientUtil;
import cn.hengzhu.main_manager.utils.RedisUtil;
import cn.hengzhu.main_manager.utils.config.gzh.WeiXinConst;
import redis.clients.jedis.exceptions.JedisConnectionException;

@Service
@Transactional(rollbackFor = Exception.class)
public class ManageCaseServiceImpl implements ManageCaseService {

	private static Logger log = Logger.getLogger(ManageCaseServiceImpl.class);

	@Autowired
	private ManageCaseBoxMapper manageCaseBoxMapper;
	@Autowired
	private ManageCaseMapper manageCaseMapper;
	@Autowired
	private SysConstMapper sysConstMapper;
	@Autowired
	private ManageCaseTypeMapper manageCaseTypeMapper;

	@Autowired
	private RedisUtil redisUtil;

	private ReentrantLock reentrantLock = new ReentrantLock();

	/**
	 * @author 刘成
	 * @since 2018年9月5日
	 * @param copyList
	 *            对柜子状态的处理
	 */
	public void doCaseWork(List<CaseInitVO> copyList) {

		log.info("心跳处理,心跳个数：" + copyList.size());

		Date date = new Date();
		// 对消息队列里的消息进行分组
		Map<String, List<CaseInitVO>> caseByMacMap = copyList.stream()
				.collect(Collectors.groupingBy(CaseInitVO::getCabinet_ID));

		System.err.println(String.valueOf(caseByMacMap));


		/*List<String> caseNoList = caseByMacMap.keySet().stream().collect(Collectors.toList());
		// 查询useTime的数据库
		ManageCaseUsetimeExample manageCaseUsetimeExample = new ManageCaseUsetimeExample();
		List<ManageCaseUsetime> manageCaseUsetimeList = manageCaseUsetimeMapper
				.selectByExample(manageCaseUsetimeExample);
		List<String> useTimeCaseNoList = manageCaseUsetimeList.stream()
				.collect(Collectors.mapping(ManageCaseUsetime::getCaseNo, Collectors.toList()));

		caseNoList.removeAll(useTimeCaseNoList);
		// 插入柜子的使用期限，默认为一天
		if (!caseNoList.isEmpty()) {
			log.info("插入柜子的使用期限1天");
			System.out.println("插入柜子的使用期限");
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.DAY_OF_MONTH, 1);
			for (String caseNo : caseNoList) {
				CaseInitVO caseInitVO = caseByMacMap.get(caseNo).get(0);
				ManageCaseUsetime record = new ManageCaseUsetime();
				record.setCaseNo(caseNo);
				record.setCreateTime(date);
				record.setLatitude(caseInitVO.getLatitude());
				record.setLongitude(caseInitVO.getLongitude());
				record.setUseEndTime(calendar.getTime());
				manageCaseUsetimeMapper.insertSelective(record);
			}
		}*/

		// 获取消息队列MAC值
		List<String> caseNoListByQue = copyList.stream()
				.collect(Collectors.mapping(CaseInitVO::getCabinet_ID, Collectors.toList())).stream().distinct()
				.collect(Collectors.toList());
		// 查询数据库所有的储物柜数据
		List<ManageCase> caseList = manageCaseMapper.getAllCase();
		// 对数据库进行分组
		Map<String, List<ManageCase>> caseByMacMapByDB = caseList.stream()
				.collect(Collectors.groupingBy(ManageCase::getCaseNo));
		// 获取数据库的MAC值
		List<String> caseNoListBySelect = caseList.stream()
				.collect(Collectors.mapping(ManageCase::getCaseNo, Collectors.toList())).stream().distinct()
				.collect(Collectors.toList());

		// 1、筛选出数据库和消息队列都有的，更新数据
		List<String> commonCaseNo = caseNoListBySelect.stream().filter((String s) -> caseNoListByQue.contains(s))
				.collect(Collectors.toList());
		List<ManageCase> updateCaseList = new ArrayList<>();
		// 需要删除或添加的储物柜列表
		List<String> insOrDelCaseNoList = new ArrayList<>();
		if (!commonCaseNo.isEmpty()) {
			log.info("筛选出数据库和消息队列都有的，更新数据");
			commonCaseNo.forEach(a -> {
				CaseInitVO caseInitVO = caseByMacMap.get(a).get(0);
				ManageCase manageCase = new ManageCase();
				Integer boxNum = caseInitVO.getDoor_status().size();
				Integer boxSum = caseByMacMapByDB.get(a).get(0).getBoxSum();
				if (boxNum == 0) {
					manageCase.setIsNormal((byte) 0);
				} else {
					manageCase.setIsNormal((byte) 1);
					manageCase.setBoxSum(boxNum);
					if (!boxNum.equals(boxSum)) {
						insOrDelCaseNoList.add(a);
					}
				}
				manageCase.setCaseNo(a);
				manageCase.setIsOnline((byte) 1);
				manageCase.setLatitude(caseInitVO.getLatitude());
				manageCase.setLongitude(caseInitVO.getLongitude());
				updateCaseList.add(manageCase);
			});

			manageCaseMapper.updatList(updateCaseList);

		}
		// 判断是否有新增或减少储物柜，有的话，，，先插入过后进行更新操作
		if (!insOrDelCaseNoList.isEmpty()) {
			log.info("判断是否有新增或减少储物柜，有的话，先插入过后进行更新操作");
			insOrDelCaseNoList.stream().forEach(a -> {
				// 现在的箱子数量
				int size = caseByMacMap.get(a).get(0).getDoor_status().size();
				// 数据库的箱子数量
				Integer boxSum = caseByMacMapByDB.get(a).get(0).getBoxSum();
				// 判断增加还是减少
				if (boxSum > size) {// 删除，修改is_del
					int num = boxSum - size;
					for (int i = 0; i < num; i++) {
						ManageCaseBox manageCaseBox = new ManageCaseBox();
						manageCaseBox.setIsDel((byte) 1);
						ManageCaseBoxExample example = new ManageCaseBoxExample();
						example.createCriteria().andCaseNoEqualTo(a).andDoorNumEqualTo(boxSum - i)
								.andIsDelEqualTo((byte) 0);
						manageCaseBoxMapper.updateByExampleSelective(manageCaseBox, example);
					}

				} else {// 增加
					//查看原本存在的个数
					ManageCaseBox maxDoorNum = manageCaseBoxMapper.getMaxDoorNum(a);
					int num = size - boxSum;
					for (int i = 0; i < num; i++) {
						if(maxDoorNum!=null && maxDoorNum.getDoorNum() >= boxSum+1+i){
							ManageCaseBoxExample manageCaseBoxExample2 = new ManageCaseBoxExample();
							manageCaseBoxExample2.setOrderByClause("CREATE_TIME DESC");//如果有重复的门柜(因为包括有删除的)，选择最新的一条
							manageCaseBoxExample2.createCriteria().andDoorNumEqualTo(boxSum+1+i).andCaseNoEqualTo(a);
							ManageCaseBox selecOnetByExample = manageCaseBoxMapper.selectOneByExample(manageCaseBoxExample2);
							selecOnetByExample.setIsDel((byte) 0);
							manageCaseBoxMapper.updateByPrimaryKey(selecOnetByExample);
						}else{
							ManageCaseBox t = new ManageCaseBox();
							t.setCaseNo(a);
							t.setCreateTime(new Date());
							t.setDoorNum(boxSum + 1 + i);
							manageCaseBoxMapper.insertSelective(t);
						}
					}
				}

			});
		}
		// 更新每个储物箱
		if (commonCaseNo != null && !commonCaseNo.isEmpty()  ) {
			log.info("更新每个储物箱");
			List<ManageCaseBox> updateCaseBoxList = new ArrayList<>();
			commonCaseNo.stream().forEach(a -> {
				List<CaseInitVO> list2 = caseByMacMap.get(a);
				List<CaseByDoorVO> doorStatusList = list2.get(list2.size() - 1).getDoor_status();
				doorStatusList.forEach(b -> {
					ManageCaseBox manageCaseBoX = new ManageCaseBox();
					boolean wire_connected = b.isWire_connected();
					boolean locked = b.isLocked();

					if (wire_connected) {
						manageCaseBoX.setIsConn((byte) 1);
					} else {
						manageCaseBoX.setIsConn((byte) 0);
					}
					if (locked) {
						manageCaseBoX.setIsLocked((byte) 1);
					} else {
						manageCaseBoX.setIsLocked((byte) 0);
					}
					manageCaseBoX.setCaseNo(a);
					manageCaseBoX.setDoorNum(b.getDoor());
					updateCaseBoxList.add(manageCaseBoX);
				});
			});
			if (!updateCaseBoxList.isEmpty()) {
				manageCaseBoxMapper.updateList(updateCaseBoxList);
			}

		}

		// 2、筛选出数据库有但是消息队列没有的，，，（不在线的）
		List<String> dataHaveCaseNo = caseNoListBySelect.stream().filter((String s) -> !caseNoListByQue.contains(s))
				.collect(Collectors.toList());
		// 批量更新状态为不在线
		if (!dataHaveCaseNo.isEmpty() && dataHaveCaseNo != null) {
			ManageCase record = new ManageCase();
			record.setIsOnline((byte) 0);
			ManageCaseExample example = new ManageCaseExample();
			example.createCriteria().andCaseNoIn(dataHaveCaseNo);
			manageCaseMapper.updateByExampleSelective(record, example);
		}

		// 3、筛选出数据库没有的，但是消息队列有的，，，（新增的）
		List<String> mqHavaCaseNo = caseNoListByQue.stream().filter((String s) -> !caseNoListBySelect.contains(s))
				.collect(Collectors.toList());
		// 插入存储柜数据
		if (mqHavaCaseNo != null && !mqHavaCaseNo.isEmpty()) {
			// 新增的需要插入默认的收费类型----查询本公司的默认收费类型
			ManageCaseTypeExample manageCaseTypeExample = new ManageCaseTypeExample();
			manageCaseTypeExample.createCriteria().andCompIdEqualTo(0).andIsDefaultEqualTo((byte) 1);
			List<ManageCaseType> selectByExample = manageCaseTypeMapper.selectByExample(manageCaseTypeExample);
			mqHavaCaseNo.stream().forEach(a -> {
				try{
					CaseInitVO caseInitVO = caseByMacMap.get(a).get(0);
					List<CaseByDoorVO> door_status = caseInitVO.getDoor_status();
					ManageCase manageCase = new ManageCase();
					manageCase.setCaseNo(a);
					manageCase.setCreateTime(date);
					manageCase.setBoxSum(door_status!=null?door_status.size():0);
					manageCase.setCompId(0);
					if (!selectByExample.isEmpty()) {
						Integer typeId = selectByExample.get(0).getTypeId();
						manageCase.setTypeId(typeId);
					}
					manageCase.setIsOnline((byte) 1);
					manageCase.setLatitude(caseInitVO.getLatitude());
					manageCase.setLongitude(manageCase.getLongitude());
					manageCaseMapper.insertSelective(manageCase);
					// 插入储物柜对应的储物箱的信息
					if(door_status!=null){
						ManageCaseBox manageCaseBox = new ManageCaseBox();
						for (int i = 0; i < door_status.size(); i++) {
							manageCaseBox.setCaseNo(a);
							manageCaseBox.setCreateTime(date);
							manageCaseBox.setDoorNum(i + 1);
							manageCaseBoxMapper.insertSelective(manageCaseBox);
						}
					}
				}catch(Exception ex){

				}
			});
		}
		//执行同步缓存
		boxsInfoPutReids();
	}

	public void getToken() {
		String url = WeiXinConst.GET_ACCESS_TOKEN.replace("APPID", WeiXinConst.APPID).replace("APPSECRET",
				WeiXinConst.APPSECRET);
		String jsonStr = HttpClientUtil.httpGet(url);
		WeiXinTokenVO parseObject = JSONObject.parseObject(jsonStr, WeiXinTokenVO.class);
		String access_token = parseObject.getAccess_token();
		String key = "ACCESS_TOKEN";
		SysConst record = new SysConst();
		SysConstExample example = new SysConstExample();
		record.setValue(access_token);
		example.createCriteria().andNameEqualTo(key);
		sysConstMapper.updateByExampleSelective(record, example);
	}




	@Override
	public void boxsInfoPutReids() {
		log.info("同步缓存");
		//防止rabbit和quartz 对redis操作的并发
		reentrantLock.lock();
		try{
			//查询所有储物柜数据前，判断心跳缓存和数据库缓存在线柜是否一致，不一致则在查询所有数据去更新数据
			Set<Serializable> mqOnLineKeys = redisUtil.getKeys(RedisUtil.ON_LINE_BOX);
			Set<Serializable> dataOnLineKeys = redisUtil.getKeys(RedisUtil.DATA_BASE_BOX_ON_LINE);

			//过滤出数据库在线而心跳中不存在的数据
			Set<Serializable> filter = dataOnLineKeys.stream().filter(item -> !mqOnLineKeys.contains(
					//onLineBox:ThreadGroup1-1 和 dataBaseBox:onLine:ThreadGroup1 空间名不一样所有替换
					String.valueOf(item).replace(RedisUtil.DATA_BASE_BOX_ON_LINE,RedisUtil.ON_LINE_BOX)
			)).collect(Collectors.toSet());
			if((filter!=null && !filter.isEmpty()) || (mqOnLineKeys==null || mqOnLineKeys.isEmpty())){
				List<String> caseNoList = new ArrayList<>();
				Set<Serializable> tempList = filter;
				if(mqOnLineKeys==null|| mqOnLineKeys.isEmpty()){
					//全部不在线
					tempList = dataOnLineKeys;
				}

				tempList.forEach(item->{
					CaseInfoPutRedisVO getRedisCase = (CaseInfoPutRedisVO)redisUtil.get(String.valueOf(item));
					if(getRedisCase!=null)caseNoList.add(getRedisCase.getCaseNo());
				});
				if(caseNoList!=null && !caseNoList.isEmpty()){
					ManageCaseExample manageCaseExample = new ManageCaseExample();
					manageCaseExample.createCriteria().andCaseNoIn(caseNoList);
					ManageCase manageCase = new ManageCase();
					manageCase.setIsOnline((byte)0);
					manageCaseMapper.updateByExampleSelective(manageCase,manageCaseExample);
				}
			}

			//获取所有柜门必要信息
			List<CaseByDoorPutReidsVO> boxConnAndLockedAll = manageCaseBoxMapper.getBoxConnAndLockedAll();
			Map<String, List<CaseByDoorPutReidsVO>> mcbsByCaseNo = boxConnAndLockedAll.stream().collect(Collectors.groupingBy(CaseByDoorPutReidsVO::getCaseNo));
			//获取所有储物柜信息
			List<ManageCase> allCase = manageCaseMapper.getAllCase();
			if(allCase!=null && !allCase.isEmpty()){
				//删除所有从数据库存的缓存，从新生成
				redisUtil.delKeys(RedisUtil.DATA_BASE_BOX_NOT_LINE);
				redisUtil.delKeys(RedisUtil.DATA_BASE_BOX_ON_LINE);
				allCase.forEach(mc->{
					CaseInfoPutRedisVO putRedisVO = new CaseInfoPutRedisVO();
					putRedisVO.setCaseNo(mc.getCaseNo());
					putRedisVO.setLatitude(mc.getLatitude());
					putRedisVO.setLongitude(mc.getLongitude());
					putRedisVO.setCaseBoxList(mcbsByCaseNo.get(mc.getCaseNo()));
					String key = RedisUtil.removeStrSymbol(putRedisVO.getCaseNo());
					if(mc.getIsOnline()==1){//在线
						redisUtil.set(RedisUtil.DATA_BASE_BOX_ON_LINE+key,putRedisVO);
					}else{
						redisUtil.set(RedisUtil.DATA_BASE_BOX_NOT_LINE+key,putRedisVO);
					}
				});
			}
			if(!QuertzTask.isConnRedisFlag)
				QuertzTask.isConnRedisFlag = true;

		}catch (Exception e){
			if(e instanceof RedisConnectionFailureException){
				log.info("redis链接异常");
				if(QuertzTask.isConnRedisFlag)
					QuertzTask.isConnRedisFlag = false;
			}
		}finally {
			reentrantLock.unlock();
		}
	}

	/**
	 * 发送的储物柜信息与reids缓存中的对比,不同则修改数据库储物柜数据
	 */
	@Override
	public void redisCacheValidata(CaseInitVO readValue) {
		// 忽略掉2分钟前的心跳数据
		if(readValue!=null && System.currentTimeMillis() - Long.parseLong(readValue.getTimestamp()) < 2L * 60L * 1000L) {
			//防止rabbit和quartz 对redis操作的并发
			reentrantLock.lock();
			try {
				//case:储物柜
				CaseInfoPutRedisVO putRedisVO = new CaseInfoPutRedisVO();
				putRedisVO.setCaseNo(readValue.getCabinet_ID());
				putRedisVO.setLatitude(readValue.getLatitude());
				putRedisVO.setLongitude(readValue.getLongitude());
				//casebox：门柜
				List<CaseByDoorVO> doorStatus = readValue.getDoor_status();
				List<CaseByDoorPutReidsVO> putReidsCaseBoxList = new ArrayList<CaseByDoorPutReidsVO>();
				if (doorStatus != null) {
					putReidsCaseBoxList = doorStatus.stream().map(item -> new CaseByDoorPutReidsVO(
							readValue.getCabinet_ID(),
							item.getDoor(),
							item.isWire_connected() == true ? (byte) 1 : 0,
							item.isLocked() == true ? (byte) 1 : 0))
							.collect(Collectors.toList());
				}
				putRedisVO.setCaseBoxList(putReidsCaseBoxList);
				//添加到在线（非数据库中在线有ttl的）
				redisUtil.set(RedisUtil.ON_LINE_BOX + RedisUtil.removeStrSymbol(readValue.getCabinet_ID()), putRedisVO, 65);

				String onLineKey = RedisUtil.DATA_BASE_BOX_ON_LINE + RedisUtil.removeStrSymbol(readValue.getCabinet_ID());
				String notLinekey = RedisUtil.DATA_BASE_BOX_NOT_LINE + RedisUtil.removeStrSymbol(readValue.getCabinet_ID());

				//筛选出数据库没有的，但是消息队列有的，新增的储物柜
				if (!redisUtil.exists(onLineKey) && !redisUtil.exists(notLinekey)) {
					log.info("database/redis:两者都不存在,新增储物柜:"+readValue.getCabinet_ID());
					addCase(putRedisVO);
				}

				//此储物柜在数据库中不在线
				if (redisUtil.exists(notLinekey)) {
					log.info("database/redis:"+readValue.getCabinet_ID()+"在线不一致");
					boxNotLine(readValue.getCabinet_ID());
				}

				//柜门数量是否一致
				CaseInfoPutRedisVO getRedisCase = (CaseInfoPutRedisVO) redisUtil.get(onLineKey);
				if (getRedisCase != null) {
					List<CaseByDoorPutReidsVO> getReidsCaseBoxList = getRedisCase.getCaseBoxList();
					if (getReidsCaseBoxList == null) {
						getReidsCaseBoxList = new ArrayList<CaseByDoorPutReidsVO>();
					}
					if (putReidsCaseBoxList.size() != getReidsCaseBoxList.size()) {
						log.info("database/redis:"+readValue.getCabinet_ID()+"门柜数量不一致");
						boxSumUnlike(getRedisCase.getCaseNo(), putReidsCaseBoxList, getReidsCaseBoxList);
					}
					//根据doorNum门号获取casebox信息
					List<ManageCaseBox> connLockedUnlike = new ArrayList<ManageCaseBox>();
					Map<Integer, CaseByDoorPutReidsVO> caseBoxByDoorNum = putReidsCaseBoxList.stream().collect(Collectors.toMap(CaseByDoorPutReidsVO::getDoorNum, v -> v));
					getReidsCaseBoxList.forEach(item -> {
						CaseByDoorPutReidsVO item2 = caseBoxByDoorNum.get(item.getDoorNum());
						//判断数据库中的casebox信息是否和心跳发送的一致
						if (item2 != null && (Byte.valueOf(item.getIsConn()) != Byte.valueOf(item2.getIsConn()) ||
								Byte.valueOf(item.getIsLocked()) != Byte.valueOf(item2.getIsLocked()))) {
							ManageCaseBox mcb = new ManageCaseBox();
							mcb.setCaseNo(item2.getCaseNo());
							mcb.setDoorNum(item2.getDoorNum());
							mcb.setIsConn(item2.getIsConn());
							mcb.setIsLocked(item2.getIsLocked());
							connLockedUnlike.add(mcb);
						}
					});

					if (connLockedUnlike != null && !connLockedUnlike.isEmpty()) {
						log.info("database/redis:"+readValue.getCabinet_ID()+"门柜、锁状态不一致");
						baseBoxInfoUnlike(connLockedUnlike);
					}
				}
			}catch (Exception e){
				if(e instanceof JedisConnectionException){
					log.info("redis链接异常");
					QuertzTask.isConnRedisFlag = false;
				}
			}finally {
				reentrantLock.unlock();
			}
		}
	}

	/**
	 * 数据库不存在，新增的储物柜
	 * @param putRedisVO 储物柜信息
	 */
	public void addCase(CaseInfoPutRedisVO putRedisVO){
		Date date = new Date();
		String caseNo = putRedisVO.getCaseNo();
		//查询数据库是否不存在
		ManageCaseExample manageCaseExample = new ManageCaseExample();
		manageCaseExample.createCriteria().andCaseNoEqualTo(caseNo);

		//若reids缓存中不存在，数据库中存在；执行数据同步
		long mcCount = manageCaseMapper.countByExample(manageCaseExample);
		if(mcCount != 0){
			boxsInfoPutReids();
			return;
		}

		// 新增的需要插入默认的收费类型----查询本公司的默认收费类型\
		ManageCaseTypeExample manageCaseTypeExample = new ManageCaseTypeExample();
		manageCaseTypeExample.createCriteria().andCompIdEqualTo(0).andIsDefaultEqualTo((byte) 1);
		List<ManageCaseType> selectByExample = manageCaseTypeMapper.selectByExample(manageCaseTypeExample);
		try{
			List<CaseByDoorPutReidsVO> caseBoxList = putRedisVO.getCaseBoxList();
			ManageCase manageCase = new ManageCase();
			manageCase.setCaseNo(caseNo);
			manageCase.setCreateTime(date);
			manageCase.setBoxSum(caseBoxList!=null?caseBoxList.size():0);
			manageCase.setCompId(0);
			if (!selectByExample.isEmpty()) {
				Integer typeId = selectByExample.get(0).getTypeId();
				manageCase.setTypeId(typeId);
			}
			manageCase.setIsOnline((byte) 1);
			manageCase.setLatitude(putRedisVO.getLatitude());
			manageCase.setLongitude(manageCase.getLongitude());
			manageCaseMapper.insertSelective(manageCase);
			// 插入储物柜对应的储物箱的信息,在此之前判断数据库是否存在该储物柜柜门
			ManageCaseBoxExample manageCaseBoxExample = new ManageCaseBoxExample();
			manageCaseBoxExample.createCriteria().andCaseNoEqualTo(caseNo).andIsDelEqualTo((byte)0);
			List<ManageCaseBox> mcbList = manageCaseBoxMapper.selectByExample(manageCaseBoxExample);
			if(mcbList!=null && !mcbList.isEmpty()){
				boxSumUnlike(caseNo,caseBoxList,caseBoxList);
			}else if(caseBoxList!=null){
				ManageCaseBox manageCaseBox = new ManageCaseBox();
				for (int i = 0; i < caseBoxList.size(); i++) {
					manageCaseBox.setCaseNo(caseNo);
					manageCaseBox.setCreateTime(date);
					manageCaseBox.setDoorNum(i + 1);
					manageCaseBox.setIsConn((byte)caseBoxList.get(i).getIsConn());
					manageCaseBox.setIsLocked((byte)caseBoxList.get(i).getIsLocked());
					manageCaseBoxMapper.insertSelective(manageCaseBox);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}


	/**
	 * 处理储物柜不在线方法(心跳在线，数据库中不在线)
	 * 设置为在线
	 */
	public void boxNotLine(String caseNo){
		ManageCase record = new ManageCase();
		record.setIsOnline((byte) 1);
		ManageCaseExample example = new ManageCaseExample();
		example.createCriteria().andCaseNoEqualTo(caseNo);
		int update = manageCaseMapper.updateByExampleSelective(record, example);
		if(update!=0){
			/*CaseInfoPutRedisVO o = (CaseInfoPutRedisVO)redisUtil.get(RedisUtil.DATA_BASE_BOX_NOT_LINE+RedisUtil.removeStrSymbol(caseNo));
			o.setIsOnline((byte)1);
			redisUtil.set(RedisUtil.DATA_BASE_BOX_ON_LINE+RedisUtil.removeStrSymbol(caseNo),o);
			redisUtil.del(RedisUtil.DATA_BASE_BOX_NOT_LINE+RedisUtil.removeStrSymbol(caseNo));*/
			String caseNoKey = RedisUtil.removeStrSymbol(caseNo);
			redisUtil.renameKey(RedisUtil.DATA_BASE_BOX_NOT_LINE+caseNoKey, RedisUtil.DATA_BASE_BOX_ON_LINE+caseNoKey);
		}
		//查询该储物柜信息
		ManageCaseExample manageCaseExample= new ManageCaseExample();
		manageCaseExample.createCriteria().andCaseNoEqualTo(caseNo);
		List<ManageCase> mcList = manageCaseMapper.selectByExample(manageCaseExample);
		AliMsmUtils.boxEventNotify(mcList,"上线了");
		
	}

	/**
	 * 门柜数量不一致
	 * @param currentCaseBoxList 当前心跳发送的储物柜
	 * @param dabaBaseCaseBoxList 数据库存在的储物柜
	 */
	public void boxSumUnlike(String caseNo,List<CaseByDoorPutReidsVO> currentCaseBoxList,List<CaseByDoorPutReidsVO> dabaBaseCaseBoxList){
		// 现在的箱子数量
		int size = currentCaseBoxList.size();
		// 数据库的箱子数量
		Integer boxSum =dabaBaseCaseBoxList.size();
		// 判断增加还是减少
		if (boxSum > size) {// 删除，修改is_del
			int num = boxSum - size;
			for (int i = 0; i < num; i++) {
				ManageCaseBox manageCaseBox = new ManageCaseBox();
				manageCaseBox.setIsDel((byte) 1);
				ManageCaseBoxExample example = new ManageCaseBoxExample();
				example.createCriteria().andCaseNoEqualTo(caseNo).andDoorNumEqualTo(boxSum - i)
						.andIsDelEqualTo((byte) 0);
				manageCaseBoxMapper.updateByExampleSelective(manageCaseBox, example);
			}
		} else {// 增加
			//查看原本存在的个数
			ManageCaseBox maxDoorNum = manageCaseBoxMapper.getMaxDoorNum(caseNo);
			int num = size - boxSum;
			for (int i = 0; i < num; i++) {
				if(maxDoorNum!=null && maxDoorNum.getDoorNum() >= boxSum+1+i){
					ManageCaseBoxExample manageCaseBoxExample2 = new ManageCaseBoxExample();
					manageCaseBoxExample2.setOrderByClause("CREATE_TIME DESC");//如果有重复的门柜(因为包括有删除的)，选择最新的一条
					manageCaseBoxExample2.createCriteria().andDoorNumEqualTo(boxSum+1+i).andCaseNoEqualTo(caseNo);
					ManageCaseBox selecOnetByExample = manageCaseBoxMapper.selectOneByExample(manageCaseBoxExample2);
					selecOnetByExample.setIsDel((byte) 0);
					manageCaseBoxMapper.updateByPrimaryKey(selecOnetByExample);
				}else{
					ManageCaseBox t = new ManageCaseBox();
					t.setCaseNo(caseNo);
					t.setCreateTime(new Date());
					t.setDoorNum(boxSum + 1 + i);
					manageCaseBoxMapper.insertSelective(t);
				}
			}
		}
		ManageCase mc = new ManageCase();
		mc.setBoxSum(size);
		ManageCaseExample manageCaseExample= new ManageCaseExample();
		manageCaseExample.createCriteria().andCaseNoEqualTo(caseNo);
		manageCaseMapper.updateByExampleSelective(mc, manageCaseExample);


	}

	/**
	 * 门柜、锁状态不一致
	 */
	public void baseBoxInfoUnlike(List<ManageCaseBox> connLockedUnlike){
		connLockedUnlike.forEach(item->{
			ManageCaseBoxExample example = new ManageCaseBoxExample();
			example.createCriteria().andCaseNoEqualTo(connLockedUnlike.get(0).getCaseNo()).andDoorNumEqualTo(item.getDoorNum())
					.andIsDelEqualTo((byte) 0);
			manageCaseBoxMapper.updateByExampleSelective(item, example);
		});
	}

}